package com.danciyixue.boot.dcyx.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.danciyixue.boot.client.test.model.UnitTestItem;
import com.danciyixue.boot.client.test.model.UnitTestQuery;
import com.danciyixue.boot.dcyx.model.entity.Units;
import com.danciyixue.boot.dcyx.service.UnitsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.danciyixue.boot.dcyx.mapper.TestsMapper;
import com.danciyixue.boot.dcyx.service.TestsService;
import com.danciyixue.boot.dcyx.service.WordsService;
import com.danciyixue.boot.dcyx.service.TestRecordsService;
import com.danciyixue.boot.dcyx.service.TestQuestionsService;
import com.danciyixue.boot.dcyx.service.TestAnswersService;
import com.danciyixue.boot.dcyx.mapper.TestQuestionsMapper;
import com.danciyixue.boot.dcyx.mapper.TestAnswersMapper;
import com.danciyixue.boot.dcyx.model.entity.Tests;
import com.danciyixue.boot.dcyx.model.entity.Words;
import com.danciyixue.boot.dcyx.model.entity.TestQuestions;
import com.danciyixue.boot.dcyx.model.entity.TestAnswers;
import com.danciyixue.boot.dcyx.model.entity.QuestionType;
import com.danciyixue.boot.dcyx.model.form.TestsForm;
import com.danciyixue.boot.dcyx.model.query.TestsQuery;
import com.danciyixue.boot.dcyx.model.vo.TestsVO;
import com.danciyixue.boot.dcyx.model.vo.PreTestVO;
import com.danciyixue.boot.dcyx.model.vo.PreTestQuestionVO;
import com.danciyixue.boot.dcyx.model.vo.PreTestAnswerVO;
import com.danciyixue.boot.dcyx.converter.TestsConverter;
import com.danciyixue.boot.core.security.util.SecurityUtils;
import com.danciyixue.boot.common.exception.BusinessException;

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 测试试卷信息服务实现类
 *
 * @author youlaitech
 * @since 2025-06-15 16:21
 */
@Service
@DS("dcyx")
@RequiredArgsConstructor
public class TestsServiceImpl extends ServiceImpl<TestsMapper, Tests> implements TestsService {

    private final TestsConverter testsConverter;
    private final WordsService wordsService;
    private final TestRecordsService testRecordsService;
    private final TestQuestionsService testQuestionsService;
    private final TestAnswersService testAnswersService;
    private final TestQuestionsMapper testQuestionsMapper;
    private final TestAnswersMapper testAnswersMapper;
    private final UnitsService unitsService;

    /**
    * 获取测试试卷信息分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<TestsVO>} 测试试卷信息分页列表
    */
    @Override
    public IPage<TestsVO> getTestsPage(TestsQuery queryParams) {
        Page<TestsVO> pageVO = this.baseMapper.getTestsPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取测试试卷信息表单数据
     *
     * @param id 测试试卷信息ID
     * @return 测试试卷信息表单数据
     */
    @Override
    public TestsForm getTestsFormData(Long id) {
        Tests entity = this.getById(id);
        return testsConverter.toForm(entity);
    }
    
    /**
     * 新增测试试卷信息
     *
     * @param formData 测试试卷信息表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveTests(TestsForm formData) {
        Tests entity = testsConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新测试试卷信息
     *
     * @param id   测试试卷信息ID
     * @param formData 测试试卷信息表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateTests(Long id,TestsForm formData) {
        Tests entity = testsConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除测试试卷信息
     *
     * @param ids 测试试卷信息ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteTestss(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的测试试卷信息数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    /**
     * 获取学前测试
     *
     * @param programId 教材ID
     * @return 学前测试数据
     */
    @Override
    @Transactional
    public PreTestVO getPreTest(Long programId) {
        return getPreTest(programId, false);
    }

    /**
     * 获取学前测试
     *
     * @param programId 教材ID
     * @param shuffle 是否重新生成试卷
     * @return 学前测试数据
     */
    @Override
    @Transactional
    public PreTestVO getPreTest(Long programId, Boolean shuffle) {
        // 获取当前用户ID
        Long userId = SecurityUtils.getUserId();
//        if (userId == null) {
//            throw new BusinessException("用户未登录");
//        }

        // 检查用户是否已完成该教材的学前测试
        if (testRecordsService.hasCompletedPreTest(userId, programId)) {
            throw new BusinessException("您已完成该教材的学前测试，无法重复测试");
        }

        // 如果不需要重新生成，先查询已存在的测试
        if (!shuffle) {
            Tests existingTest = this.baseMapper.findByProgramIdAndType(programId, 1);
            if (existingTest != null) {
                return buildPreTestVOFromExistingTest(existingTest);
            }
        }

        // 生成新的测试试卷
        return generateNewPreTest(programId);
    }

    /**
     * 生成英译中题目
     */
    private List<PreTestQuestionVO> generateEtcQuestions(List<Words> targetWords, List<Words> allWords) {
        return targetWords.stream()
                .map(word -> {
                    PreTestQuestionVO question = new PreTestQuestionVO();
                    question.setWordId(word.getId());
                    question.setSpelling(word.getSpelling());
                    question.setMeaning(word.getMeaningZhCn());
                    question.setAnswers(generateEtcAnswers(word, allWords));
                    return question;
                })
                .collect(Collectors.toList());
    }

    /**
     * 生成中译英题目
     */
    private List<PreTestQuestionVO> generateCteQuestions(List<Words> targetWords, List<Words> allWords) {
        return targetWords.stream()
                .map(word -> {
                    PreTestQuestionVO question = new PreTestQuestionVO();
                    question.setWordId(word.getId());
                    question.setSpelling(word.getSpelling());
                    question.setMeaning(word.getMeaningZhCn());
                    question.setAnswers(generateCteAnswers(word, allWords));
                    return question;
                })
                .collect(Collectors.toList());
    }

    /**
     * 生成听力题目
     */
    private List<PreTestQuestionVO> generateHearingQuestions(List<Words> targetWords, List<Words> allWords) {
        return targetWords.stream()
                .map(word -> {
                    PreTestQuestionVO question = new PreTestQuestionVO();
                    question.setWordId(word.getId());
                    question.setSpelling(word.getSpelling());
                    question.setMeaning(word.getMeaningZhCn());
                    question.setAnswers(generateHearingAnswers(word, allWords));
                    return question;
                })
                .collect(Collectors.toList());
    }

    /**
     * 生成英译中答案选项（显示英文，选择中文释义）
     */
    private List<PreTestAnswerVO> generateEtcAnswers(Words correctWord, List<Words> allWords) {
        List<PreTestAnswerVO> answers = new ArrayList<>();

        // 正确答案
        PreTestAnswerVO correctAnswer = new PreTestAnswerVO();
        correctAnswer.setSpelling(correctWord.getMeaningZhCn());
        correctAnswer.setMeaning(correctWord.getMeaningZhCn());
        correctAnswer.setCorrect(1);
        answers.add(correctAnswer);

        // 生成3个干扰项
        List<Words> distractors = allWords.stream()
                .filter(word -> !word.getId().equals(correctWord.getId()))
                .filter(word -> StrUtil.isNotBlank(word.getMeaningZhCn()))
                .collect(Collectors.toList());

        Collections.shuffle(distractors);
        distractors.stream()
                .limit(3)
                .forEach(word -> {
                    PreTestAnswerVO distractor = new PreTestAnswerVO();
                    distractor.setSpelling(word.getMeaningZhCn());
                    distractor.setMeaning(word.getMeaningZhCn());
                    distractor.setCorrect(0);
                    answers.add(distractor);
                });

        // 随机打乱答案顺序
        Collections.shuffle(answers);
        return answers;
    }

    /**
     * 生成中译英答案选项（显示中文，选择英文拼写）
     */
    private List<PreTestAnswerVO> generateCteAnswers(Words correctWord, List<Words> allWords) {
        List<PreTestAnswerVO> answers = new ArrayList<>();

        // 正确答案
        PreTestAnswerVO correctAnswer = new PreTestAnswerVO();
        correctAnswer.setSpelling(correctWord.getSpelling());
        correctAnswer.setMeaning(correctWord.getMeaningZhCn());
        correctAnswer.setCorrect(1);
        answers.add(correctAnswer);

        // 生成3个干扰项
        List<Words> distractors = allWords.stream()
                .filter(word -> !word.getId().equals(correctWord.getId()))
                .filter(word -> StrUtil.isNotBlank(word.getSpelling()))
                .collect(Collectors.toList());

        Collections.shuffle(distractors);
        distractors.stream()
                .limit(3)
                .forEach(word -> {
                    PreTestAnswerVO distractor = new PreTestAnswerVO();
                    distractor.setSpelling(word.getSpelling());
                    distractor.setMeaning(word.getMeaningZhCn());
                    distractor.setCorrect(0);
                    answers.add(distractor);
                });

        // 随机打乱答案顺序
        Collections.shuffle(answers);
        return answers;
    }

    /**
     * 生成听力答案选项（播放发音，选择正确拼写）
     */
    private List<PreTestAnswerVO> generateHearingAnswers(Words correctWord, List<Words> allWords) {
        List<PreTestAnswerVO> answers = new ArrayList<>();

        // 正确答案
        PreTestAnswerVO correctAnswer = new PreTestAnswerVO();
        correctAnswer.setSpelling(correctWord.getSpelling());
        correctAnswer.setMeaning(correctWord.getMeaningZhCn());
        correctAnswer.setCorrect(1);
        answers.add(correctAnswer);

        // 生成3个干扰项
        List<Words> distractors = allWords.stream()
                .filter(word -> !word.getId().equals(correctWord.getId()))
                .filter(word -> StrUtil.isNotBlank(word.getSpelling()))
                .collect(Collectors.toList());

        Collections.shuffle(distractors);
        distractors.stream()
                .limit(3)
                .forEach(word -> {
                    PreTestAnswerVO distractor = new PreTestAnswerVO();
                    distractor.setSpelling(word.getSpelling());
                    distractor.setMeaning(word.getMeaningZhCn());
                    distractor.setCorrect(0);
                    answers.add(distractor);
                });

        // 随机打乱答案顺序
        Collections.shuffle(answers);
        return answers;
    }

    /**
     * 创建并保存测试试卷
     */
    private Tests createAndSaveTest(Long programId) {
        Tests test = new Tests();
        test.setProgramId(programId);
        test.setTitle("学前测试");
        test.setType(1);
        test.setSecond(3000);
        test.setTotalQuestionNum(30);

        this.save(test);
        return test;
    }

    /**
     * 生成并保存测试题目和答案
     */
    private void generateAndSaveTestData(Long testId, List<Words> testWords, List<Words> distractorWords) {
        // 分配题目类型：前10个为英译中，中间10个为中译英，后10个为听力
        List<QuestionType> questionTypes = List.of(
                QuestionType.ETC_TRANSLATION, QuestionType.ETC_TRANSLATION, QuestionType.ETC_TRANSLATION,
                QuestionType.ETC_TRANSLATION, QuestionType.ETC_TRANSLATION, QuestionType.ETC_TRANSLATION,
                QuestionType.ETC_TRANSLATION, QuestionType.ETC_TRANSLATION, QuestionType.ETC_TRANSLATION,
                QuestionType.ETC_TRANSLATION,
                QuestionType.CTE_TRANSLATION, QuestionType.CTE_TRANSLATION, QuestionType.CTE_TRANSLATION,
                QuestionType.CTE_TRANSLATION, QuestionType.CTE_TRANSLATION, QuestionType.CTE_TRANSLATION,
                QuestionType.CTE_TRANSLATION, QuestionType.CTE_TRANSLATION, QuestionType.CTE_TRANSLATION,
                QuestionType.CTE_TRANSLATION,
                QuestionType.HEARING_TRANSLATION, QuestionType.HEARING_TRANSLATION, QuestionType.HEARING_TRANSLATION,
                QuestionType.HEARING_TRANSLATION, QuestionType.HEARING_TRANSLATION, QuestionType.HEARING_TRANSLATION,
                QuestionType.HEARING_TRANSLATION, QuestionType.HEARING_TRANSLATION, QuestionType.HEARING_TRANSLATION,
                QuestionType.HEARING_TRANSLATION
        );

        for (int i = 0; i < testWords.size(); i++) {
            Words word = testWords.get(i);
            QuestionType questionType = questionTypes.get(i);

            // 创建并保存测试题目
            TestQuestions question = createTestQuestion(testId, word.getId(), questionType);
            testQuestionsService.save(question);

            // 为每个题目生成4个答案选项（1个正确答案 + 3个干扰项）
            generateAndSaveAnswers(question.getId(), word, distractorWords, questionType);
        }
    }

    /**
     * 创建测试题目
     */
    private TestQuestions createTestQuestion(Long testId, Long wordId, QuestionType questionType) {
        TestQuestions question = new TestQuestions();
        question.setTestId(testId);
        question.setWordId(wordId);
        question.setQuestionType(questionType);
        question.setIsChecked(0);
        return question;
    }

    /**
     * 生成并保存答案选项
     */
    private void generateAndSaveAnswers(Long questionId, Words correctWord, List<Words> distractorWords, QuestionType questionType) {
        List<TestAnswers> answers = new ArrayList<>();

        // 添加正确答案
        TestAnswers correctAnswer = createCorrectAnswer(questionId, correctWord, questionType);
        answers.add(correctAnswer);

        // 添加3个干扰项
        List<TestAnswers> distractors = createDistractorAnswers(questionId, correctWord, distractorWords, questionType);
        answers.addAll(distractors);

        // 批量保存答案
        testAnswersService.saveBatch(answers);
    }

    /**
     * 创建正确答案
     */
    private TestAnswers createCorrectAnswer(Long questionId, Words correctWord, QuestionType questionType) {
        TestAnswers answer = new TestAnswers();
        answer.setQuestionId(questionId);
        answer.setCorrect(1);
        answer.setCorrectWordId(correctWord.getId());
        answer.setRealWordId(correctWord.getId());
        answer.setDisabled(0);

        switch (questionType) {
            case ETC_TRANSLATION:
                answer.setSpelling(correctWord.getMeaningZhCn());
                answer.setMeaning(correctWord.getMeaningZhCn());
                break;
            case CTE_TRANSLATION:
            case HEARING_TRANSLATION:
                answer.setSpelling(correctWord.getSpelling());
                answer.setMeaning(correctWord.getMeaningZhCn());
                break;
        }

        return answer;
    }

    /**
     * 创建干扰项答案
     */
    private List<TestAnswers> createDistractorAnswers(Long questionId, Words correctWord, List<Words> distractorWords, QuestionType questionType) {
        List<TestAnswers> distractors = new ArrayList<>();

        // 从干扰单词中随机选择3个不同的单词
        List<Words> shuffledDistractors = new ArrayList<>(distractorWords);
        Collections.shuffle(shuffledDistractors);

        shuffledDistractors.stream()
                .filter(word -> !word.getId().equals(correctWord.getId()))
                .filter(word -> StrUtil.isNotBlank(word.getSpelling()) && StrUtil.isNotBlank(word.getMeaningZhCn()))
                .limit(3)
                .forEach(word -> {
                    TestAnswers distractor = new TestAnswers();
                    distractor.setQuestionId(questionId);
                    distractor.setCorrect(0);
                    distractor.setCorrectWordId(correctWord.getId());
                    distractor.setRealWordId(word.getId());
                    distractor.setDisabled(0);

                    switch (questionType) {
                        case ETC_TRANSLATION:
                            distractor.setSpelling(word.getMeaningZhCn());
                            distractor.setMeaning(word.getMeaningZhCn());
                            break;
                        case CTE_TRANSLATION:
                        case HEARING_TRANSLATION:
                            distractor.setSpelling(word.getSpelling());
                            distractor.setMeaning(word.getMeaningZhCn());
                            break;
                    }

                    distractors.add(distractor);
                });

        return distractors;
    }

    /**
     * 从已存在的测试构建 PreTestVO
     */
    private PreTestVO buildPreTestVOFromExistingTest(Tests existingTest) {
        // 查询测试题目
        List<TestQuestions> questions = testQuestionsMapper.findByTestId(existingTest.getId());

        // 按题目类型分组
        List<TestQuestions> etcQuestions = questions.stream()
                .filter(q -> QuestionType.ETC_TRANSLATION.equals(q.getQuestionType()))
                .collect(Collectors.toList());
        List<TestQuestions> cteQuestions = questions.stream()
                .filter(q -> QuestionType.CTE_TRANSLATION.equals(q.getQuestionType()))
                .collect(Collectors.toList());
        List<TestQuestions> hearingQuestions = questions.stream()
                .filter(q -> QuestionType.HEARING_TRANSLATION.equals(q.getQuestionType()))
                .collect(Collectors.toList());

        // 构建 PreTestVO
        PreTestVO preTestVO = new PreTestVO();
        preTestVO.setTestId(existingTest.getId());
        preTestVO.setTitle(existingTest.getTitle());
        preTestVO.setType(existingTest.getType());
        preTestVO.setSecond(String.valueOf(existingTest.getSecond()));
        preTestVO.setTotalQuestionNum(String.valueOf(existingTest.getTotalQuestionNum()));

        // 构建题目和答案
        preTestVO.setEtcTranslation(buildQuestionsFromDatabase(etcQuestions));
        preTestVO.setCteTranslation(buildQuestionsFromDatabase(cteQuestions));
        preTestVO.setHearingTranslation(buildQuestionsFromDatabase(hearingQuestions));

        return preTestVO;
    }

    /**
     * 从数据库构建题目列表
     */
    private List<PreTestQuestionVO> buildQuestionsFromDatabase(List<TestQuestions> questions) {
        return questions.stream()
                .map(question -> {
                    // 查询单词信息
                    Words word = wordsService.getById(question.getWordId());
                    if (word == null) {
                        return null;
                    }

                    // 查询答案选项
                    List<TestAnswers> answers = testAnswersMapper.findByQuestionId(question.getId());

                    PreTestQuestionVO questionVO = new PreTestQuestionVO();
                    questionVO.setWordId(word.getId());
                    questionVO.setSpelling(word.getSpelling());
                    questionVO.setMeaning(word.getMeaningZhCn());
                    questionVO.setAnswers(buildAnswersFromDatabase(answers));

                    return questionVO;
                })
                .filter(q -> q != null)
                .collect(Collectors.toList());
    }

    /**
     * 从数据库构建答案选项列表
     */
    private List<PreTestAnswerVO> buildAnswersFromDatabase(List<TestAnswers> answers) {
        return answers.stream()
                .map(answer -> {
                    PreTestAnswerVO answerVO = new PreTestAnswerVO();
                    answerVO.setSpelling(answer.getSpelling());
                    answerVO.setMeaning(answer.getMeaning());
                    answerVO.setCorrect(answer.getCorrect());
                    return answerVO;
                })
                .collect(Collectors.toList());
    }

    /**
     * 生成新的学前测试
     */
    private PreTestVO generateNewPreTest(Long programId) {
        // 随机获取120个单词（30个测试单词 + 90个干扰单词）
        List<Words> allWords = wordsService.getRandomWordsByProgramId(programId, 120);
        if (allWords.size() < 120) {
            throw new BusinessException("该教材单词数量不足，无法生成学前测试");
        }

        // 前30个作为测试单词，后90个作为干扰单词
        List<Words> testWords = allWords.subList(0, 30);
        List<Words> distractorWords = allWords.subList(30, 120);

        // 创建并保存测试试卷
        Tests test = createAndSaveTest(programId);

        // 生成并保存测试题目和答案
        generateAndSaveTestData(test.getId(), testWords, distractorWords);

        // 构建学前测试数据
        PreTestVO preTestVO = new PreTestVO();
        preTestVO.setTestId(test.getId());
        preTestVO.setTitle("学前测试");
        preTestVO.setType(1);
        preTestVO.setSecond("3000");
        preTestVO.setTotalQuestionNum("30");

        // 分配题目：前10个为英译中，中间10个为中译英，后10个为听力
        preTestVO.setEtcTranslation(generateEtcQuestions(testWords.subList(0, 10), allWords));
        preTestVO.setCteTranslation(generateCteQuestions(testWords.subList(10, 20), allWords));
        preTestVO.setHearingTranslation(generateHearingQuestions(testWords.subList(20, 30), allWords));

        return preTestVO;
    }

    /**
     * 获取单元测试项列表
     *
     * @param queryParams 查询参数
     * @return 单元测试项分页列表
     */
    @Override
    public IPage<UnitTestItem> getUnitTestItems(UnitTestQuery queryParams) {
        // 获取当前用户ID
        Long userId = SecurityUtils.getUserId();

        Page<UnitTestItem> page = this.baseMapper.getUnitTestItems(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams,
                userId
        );
        return page;
    }

    /**
     * 获取单元测试试卷内容
     *
     * @param unitId 单元ID
     * @param shuffle 是否重新生成试卷
     * @return 单元测试数据
     */
    @Override
    @Transactional
    public PreTestVO getUnitTest(Long unitId, Boolean shuffle) {
        // 如果传递了 shuffle 参数且为 true，直接生成新试卷
        if (Boolean.TRUE.equals(shuffle)) {
            return generateNewUnitTest(unitId);
        }

        // 不传递 shuffle 参数或 shuffle 为 false 时，先查询已存在的测试
        Tests existingTest = this.baseMapper.findByUnitIdAndType(unitId, 2); // 单元测试类型为2
        if (existingTest != null) {
            return buildPreTestVOFromExistingTest(existingTest);
        }

        // 如果没有查询到之前的试卷，则返回一个新生成的试卷
        return generateNewUnitTest(unitId);
    }

    /**
     * 生成新的单元测试
     */
    private PreTestVO generateNewUnitTest(Long unitId) {
        // 获取该单元的所有单词
        List<Words> unitWords = wordsService.getWordsByUnitId(unitId);
        if (unitWords.isEmpty()) {
            throw new BusinessException("该单元没有单词，无法生成测试");
        }

        // 获取单元信息
        Units unit = unitsService.getById(unitId);
        if (unit == null) {
            throw new BusinessException("单元不存在");
        }

        // 获取干扰项单词：从属于该 programId 的其他 unitId 的单词列表中选择
        List<Words> distractorWords = wordsService.getRandomWordsByProgramIdExcludingUnit(
                unit.getProgramId(), unitId, unitWords.size() * 3); // 获取足够的干扰项

        if (distractorWords.size() < 3) {
            // 如果其他单元的单词不够，使用同教材的所有单词作为干扰项
            distractorWords = wordsService.getRandomWordsByProgramId(unit.getProgramId(), unitWords.size() * 3);
        }

        // 创建并保存测试试卷
        Tests test = createAndSaveUnitTest(unitId, unit.getProgramId());

        // 生成并保存测试题目和答案
        generateAndSaveUnitTestData(test.getId(), unitWords, distractorWords);

        // 构建单元测试数据
        PreTestVO unitTestVO = new PreTestVO();
        unitTestVO.setTestId(test.getId());
        unitTestVO.setTitle("单元测试 - " + unit.getNameZhCn());
        unitTestVO.setType(2);
        unitTestVO.setSecond("1800"); // 30分钟
        unitTestVO.setTotalQuestionNum(String.valueOf(unitWords.size()));

        // 将单词分为三个模块，每个模块的单词数量相等
        int wordsPerModule = unitWords.size() / 3;
        int remainder = unitWords.size() % 3;

        // 分配题目：中译英、英译中、听力默写
        List<Words> cteWords = unitWords.subList(0, wordsPerModule + (remainder > 0 ? 1 : 0));
        List<Words> etcWords = unitWords.subList(cteWords.size(), cteWords.size() + wordsPerModule + (remainder > 1 ? 1 : 0));
        List<Words> hearingWords = unitWords.subList(cteWords.size() + etcWords.size(), unitWords.size());

        // 打乱每个模块内的单词顺序
        Collections.shuffle(cteWords);
        Collections.shuffle(etcWords);
        Collections.shuffle(hearingWords);

        // 使用干扰项单词生成题目
        unitTestVO.setCteTranslation(generateCteQuestions(cteWords, distractorWords));
        unitTestVO.setEtcTranslation(generateEtcQuestions(etcWords, distractorWords));
        unitTestVO.setHearingTranslation(generateHearingQuestions(hearingWords, distractorWords));

        return unitTestVO;
    }

    /**
     * 创建并保存单元测试试卷
     */
    private Tests createAndSaveUnitTest(Long unitId, Long programId) {
        Tests test = new Tests();
        test.setUnitId(unitId);
        test.setProgramId(programId);
        test.setTitle("单元测试");
        test.setType(2); // 单元测试类型为2
        test.setSecond(1800); // 30分钟

        // 获取单元单词数量
        List<Words> unitWords = wordsService.getWordsByUnitId(unitId);
        test.setTotalQuestionNum(unitWords.size());

        this.save(test);
        return test;
    }

    /**
     * 生成并保存单元测试数据
     */
    private void generateAndSaveUnitTestData(Long testId, List<Words> unitWords, List<Words> distractorWords) {
        // 将单词分为三个模块
        int wordsPerModule = unitWords.size() / 3;
        int remainder = unitWords.size() % 3;

        List<QuestionType> questionTypes = new ArrayList<>();
        int cte_num = wordsPerModule + (remainder > 0 ? 1 : 0);
        int etc_num = wordsPerModule + (remainder > 1 ? 1 : 0);

        // 中译英题目
        for (int i = 0; i < cte_num; i++) {
            questionTypes.add(QuestionType.CTE_TRANSLATION);
        }

        // 英译中题目
        for (int i = 0; i < etc_num; i++) {
            questionTypes.add(QuestionType.ETC_TRANSLATION);
        }

        int h_num = unitWords.size() - questionTypes.size();
        // 听力题目
        for (int i = 0; i < h_num; i++) {
            questionTypes.add(QuestionType.HEARING_TRANSLATION);
        }

        for (int i = 0; i < unitWords.size(); i++) {
            Words word = unitWords.get(i);
            QuestionType questionType = questionTypes.get(i);

            // 创建并保存测试题目
            TestQuestions question = createTestQuestion(testId, word.getId(), questionType);
            testQuestionsService.save(question);

            // 为每个题目生成4个答案选项（1个正确答案 + 3个干扰项）
            generateAndSaveAnswers(question.getId(), word, distractorWords, questionType);
        }
    }

}
